package com.bzg.manager.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.bzg.manager.exception.BaseExceptionTool;
import com.bzg.manager.param.ReturnParam;
import com.bzg.manager.param.UserParam;
import com.bzg.manager.service.UserService;
import com.bzg.manager.utils.RespBody;
import com.wordnik.swagger.annotations.ApiOperation;

@RequestMapping("/upload")
@Controller
public class UploadController {
	
	public static final Logger log = LoggerFactory.getLogger(UploadController.class);
	
	@Autowired
	private UserService userService;
	
	@Value("${imgBasePath}")
	private String IMGBASEPATH;
	
	/*@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "上传图片")
	public RespBody imgUpload(HttpServletRequest request,@RequestParam(value = "file", required = false)MultipartFile file){
		StringBuffer requestURL = request.getRequestURL();
		System.out.println(requestURL.toString());
		if(file != null){
			//原始图片名称
			String originalFilename = file.getOriginalFilename();
			//如果没有图片名称，则上传不成功
			if(originalFilename != null && originalFilename.length()>0)
			{	
				String picPath = request.getSession().getServletContext().getRealPath("/upload");  
				//存放图片的物理路径
				//String picPath = "upload/";
				//新文件的名称
				String newFileName = UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
				//新的文件
				File newFile = new File(picPath+ "/" +newFileName);
				//把上传的文件保存成一个新的文件
				try {
					file.transferTo(newFile);
				} catch (IllegalStateException | IOException e) {
					log.error("服务器保存图片出错！");
					return RespBody.error("1007", "保存图片失败!");
				}
			}else{
				return RespBody.error("1006", "图片不存在！");
			}
		}
		return RespBody.ok("", "图片上传成功！"); 
	}*/
	
	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "上传图片")
	public RespBody uploadImg(final HttpServletRequest request,Model model){
		final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		final Map<String, MultipartFile> files = multiRequest.getFileMap();
		Iterator<Entry<String, MultipartFile>> itr = files.entrySet().iterator();
		MultipartFile file;
		String userName = request.getParameter("userName");
		if(StringUtils.isEmpty(userName)){
			throw BaseExceptionTool.PARAM_IS_NULL;
		}
		//获取用户已经存在的头像名称
		String oriUserImgName = userService.getUserImgName(userName);
		ReturnParam reParam = new ReturnParam();
		UserParam userParam = new UserParam();
		while (itr.hasNext()) {
			Entry<String, MultipartFile> entry = itr.next();
			file = entry.getValue();
			if(file != null){
				//原始图片名称
				String originalFilename = file.getOriginalFilename();
				//如果没有图片名称，则上传不成功
				if(originalFilename != null && originalFilename.length()>0)
				{
					String picPath = request.getSession().getServletContext().getRealPath("/upload");  
					//新文件的名称
					String newFileName = userName+"_"+ new Date().getTime() + originalFilename.substring(originalFilename.lastIndexOf("."));
					//新的文件
					File newFile = new File(picPath+ "/" +newFileName);
					if(newFile.exists()){
						newFile.delete();
					}
					//把上传的文件保存成一个新的文件
					try {
						file.transferTo(newFile);
						//设置图片访问路径
						reParam.setImgPath(IMGBASEPATH + newFileName);
						//将图片路径保存到数据库
						userParam.setUserName(userName);
						userParam.setImgName(newFileName);
						userService.saveImgPath(userParam);
						//当图片保存成功后删除原来的头像
						if(StringUtils.isNotEmpty(oriUserImgName)){
							File oriFile = new File(picPath+ "/" +oriUserImgName);
							if(oriFile.exists()){
								oriFile.delete();
							}
						}
					} catch (IllegalStateException | IOException e) {
						log.error("服务器保存图片出错！");
						return RespBody.error("1007", "保存图片失败!");
					}
				}else{
					return RespBody.error("1006", "图片不存在！");
				}
			}else{
				return RespBody.error("1006", "图片不存在！");
			}
		}
		return RespBody.ok(reParam, "图片上传成功！");
	}
}
